package com.sunrate.investingquote.service.router.match;

import com.alibaba.fastjson2.JSON;
import com.ql.util.express.IExpressContext;
import com.sunrate.investingquote.bean.router.ChannelRouter;
import com.sunrate.investingquote.bean.router.ChannelRouterCondition;
import com.sunrate.investingquote.dao.router.ChannelRouterConditionDao;
import com.sunrate.investingquote.dto.router.RouterMatchParam;
import com.sunrate.investingquote.util.QlExpressUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @author yyh
 * @description:
 * @date 2023/06/29/ 12:51
 */
@Service("dbExpressionMatch")
@Slf4j
public class DbExpressionMatch implements RouterMatch {

    @Autowired
    private ChannelRouterConditionDao conditionDao;

    @Override
    public boolean test(RouterMatchParam param, ChannelRouter router) {
        List<ChannelRouterCondition> conditionList = conditionDao.listByChannelCode(router.getChannelCode());
        if (CollectionUtils.isEmpty(conditionList)) {
            return true;
        }
        return conditionList.stream().allMatch(condition -> {
            String express = condition.getExpress();
            IExpressContext<String, Object> context = QlExpressUtil.beanToContext(param);
            try {
                return QlExpressUtil.execute(express, context);
            } catch (Exception e) {
                log.error("DbExpressionMatch express:{},context:{} error", express, JSON.toJSONString(context), e);
                throw new RuntimeException(e);
            }
        });
    }

    @Override
    public boolean skip() {
        return false;
    }
}
